package com.yusheng.tr.auth.controller;



import com.yusheng.constant.Constants;
import com.yusheng.domain.R;
import com.yusheng.tr.common.core.model.vo.LoginUser;
import com.yusheng.tr.common.core.service.TokenService;
import com.yusheng.tr.common.core.utils.SecurityUtils;
import com.yusheng.utils.string.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yusheng.tr.auth.form.LoginBody;
import com.yusheng.tr.auth.form.RegisterBody;
import com.yusheng.tr.auth.service.SysLoginService;
import com.yusheng.tr.common.core.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * token 控制
 *
 * @author yusheng
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class TokenController {

    @Resource
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody loginBody) {
        Map<String,Object> map = new HashMap<>();
        // 生成令牌
        String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword());
        map.put(Constants.TOKEN, token);
        return R.ok(map);
    }

    @DeleteMapping("/logout")
    public R<?> logout() {
        try {
            String token = SecurityUtils.getLoginUser().getToken();
            tokenService.delLoginUser(token);
        }catch (Exception e){
            log.info("*****{}",e.getMessage());
        }
        return R.ok();
    }

    @PostMapping("/refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("/register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
